package cn.jee.jsp;

import cn.jee.jsp.util.JdbcUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/saveStu")
public class SaveStuServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();
    String name = req.getParameter("name");
    String strJava = req.getParameter("java");
    try {
      double java = Double.parseDouble(strJava);
      if (java < 0 || java > 100) {
        throw new IllegalArgumentException("java值太大或太小");
      }
    } catch (Exception ex) {
      session.setAttribute("edit_stu_msg", ex.getMessage());
      req.getRequestDispatcher("/stu/stu_new.jsp").forward(req, resp);
      return;
    }
    String math = req.getParameter("math");
    Object clazz_id=session.getAttribute("clazz_id");
    String sql="insert into stu(name,java,math,clazz_id) values(?,?,?,?)";
    Object[] args={name,strJava,math,clazz_id};
    int row=JdbcUtil.update(sql,args);
    session.setAttribute("stu_msg",row>0?"增加学生成功":"增加学生失败");
//    showStus?clazz_id=clazz_id
    resp.sendRedirect(req.getContextPath()+"/showStus?clazz_id="+clazz_id);
  }
}
